package com.jinlejia.erp.ui.customer;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityPushFollowUpBinding;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.ui.common.SheetSelect;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

public class PushFollowUpActivity extends AppCompatActivity {
    private ActivityPushFollowUpBinding binding;
    private ProgressDialog progressDialog;
    ArrayList<Map<String, Object>> reasonList = new ArrayList<>();//跟进结果
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_push_follow_up);
        binding.setEvent(this);
        binding.etBaoPrice.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        binding.etFloorPrice.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        progressDialog = new ProgressDialog(this,"请稍后...",false);

        binding.etBaoPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start >= 0) {//从一输入就开始判断，
                    try {
                        int num = Integer.parseInt(s.toString());
                        //判断当前edittext中的数字(可能一开始Edittext中有数字)是否大于max
                        if (num > 10000) {
                            s = String.valueOf(10000);//如果大于max，则内容为max
                            binding.etBaoPrice.setText(s);
                            CustomToast.showToast(PushFollowUpActivity.this, "金额不能超过一亿",1500);

                        } else if (num <= 0) {
                            s = String.valueOf(1);//如果小于min,则内容为min
                            binding.etBaoPrice.setText(s);
                            CustomToast.showToast(PushFollowUpActivity.this, "金额不能为0",1500);
                        }
                        binding.tvSaveUnchanged.setBackgroundColor(Color.parseColor("#E0E0E0"));
                    } catch (NumberFormatException e) {
                        Log.e("ontextchanged", "==" + e.toString());
                    }
                    //edittext中的数字在max和min之间，则不做处理，正常显示即可。
                    return;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if(TextUtils.isEmpty(s)&&TextUtils.isEmpty(binding.etFloorPrice.getText())){
                    binding.tvSaveUnchanged.setBackgroundColor(Color.parseColor("#4B4948"));
                }
            }
        });

        binding.etFloorPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start >= 0) {//从一输入就开始判断，
                    try {
                        int num = Integer.parseInt(s.toString());
                        //判断当前edittext中的数字(可能一开始Edittext中有数字)是否大于max
                        if (num > 10000) {
                            s = String.valueOf(10000);//如果大于max，则内容为max
                            binding.etFloorPrice.setText(s);
                            CustomToast.showToast(PushFollowUpActivity.this, "金额不能超过一亿",1500);

                        } else if (num <= 0) {
                            s = String.valueOf(1);//如果小于min,则内容为min
                            binding.etFloorPrice.setText(s);
                            CustomToast.showToast(PushFollowUpActivity.this, "金额不能为0",1500);
                        }
                        binding.tvSaveUnchanged.setBackgroundColor(Color.parseColor("#E0E0E0"));
                    } catch (NumberFormatException e) {
                        Log.e("ontextchanged", "==" + e.toString());
                    }
                    //edittext中的数字在max和min之间，则不做处理，正常显示即可。
                    return;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if(TextUtils.isEmpty(s)&&TextUtils.isEmpty(binding.etBaoPrice.getText())){
                    binding.tvSaveUnchanged.setBackgroundColor(Color.parseColor("#4B4948"));
                }
            }
        });

        if(getIntent().getStringExtra("type").equals("sale")){
            binding.etBaoPrice.setHint("请更新报价，最高10000万");
            binding.etFloorPrice.setHint("请更新底价，最高10000万");
        }else{
            binding.etBaoPrice.setHint("请更新报价，最高100万元");
            binding.etFloorPrice.setHint("请更新底价，最高100万元");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    public void Onclick(View view){
        switch (view.getId()){
            case R.id.tvSaveUnchanged:
                if (TextUtils.isEmpty(binding.etBaoPrice.getText())||TextUtils.isEmpty(binding.etFloorPrice.getText())){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("rscode",binding.tvCode.getText().toString());
                    jsonObject.put("followStyle",binding.followMode.getText().toString());
                    jsonObject.put("followContent",binding.inputContent.getText().toString());
                    jsonObject.put("followResult",binding.followReason.getText().toString());
                    priceFollowSub(jsonObject);
                }
                break;
            case R.id.tvSaveNewPrice:
                if (TextUtils.isEmpty(binding.etBaoPrice.getText().toString())||TextUtils.isEmpty(binding.etFloorPrice.getText().toString())){
                    CustomToast.showToast(PushFollowUpActivity.this,"请填写最新价格",1500);
                }else{
                    JSONObject jsonObject2 = new JSONObject();
                    jsonObject2.put("rscode",binding.tvCode.getText().toString());
                    jsonObject2.put("followStyle",binding.followMode.getText().toString());
                    jsonObject2.put("followContent",binding.inputContent.getText().toString());
                    jsonObject2.put("followResult",binding.followReason.getText().toString());
                    jsonObject2.put("price",Double.parseDouble(binding.etBaoPrice.getText().toString()));
                    jsonObject2.put("lowPrice",Double.parseDouble(binding.etFloorPrice.getText().toString()));
                    priceFollowSub(jsonObject2);
                }
                break;
            case  R.id.rl_follow_reason:
                final SheetSelect reasonSelect = new SheetSelect(PushFollowUpActivity.this, "跟进结果", reasonList);
                reasonSelect.show();
                reasonSelect.setOnSelectListener(o -> {
                    Map<String, Object> map = (Map<String, Object>) o;
                    reasonSelect.dismiss();
                    binding.followReason.setText(map.get("valueName").toString());
                    if (!map.get("valueName").toString().equals("接通") && !map.get("valueName").toString().equals("微信或其他")) {
                        binding.inputContent.setText(map.get("valueName").toString());
                    } else {
                        binding.inputContent.setText("");
                    }

                });
                break;
            case R.id.back_btn:
                finish();
                break;
        }
    }

    //region 获取价格跟进数据
    private void getData(){
        if (progressDialog!=null && !progressDialog.isShowing()){
            progressDialog.show();
        }
        String url;
        if(getIntent().getStringExtra("type").equals("sale")){
            url = ApiConfig.INTENT_SHS_PRICE_FOLLOW;
        }else{
            url = ApiConfig.INTENT_RENT_PRICE_FOLLOW;
        }

        OkHttpUtils.get()
                .url(url.concat(getIntent().getStringExtra("rscode")))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        if (progressDialog!=null && progressDialog.isShowing()){
                            progressDialog.dismiss();
                        }
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (progressDialog!=null && progressDialog.isShowing()){
                            progressDialog.dismiss();
                        }
                        JSONObject data = JSON.parseObject(response.get("data").toString());
                        JSONObject followReadyResult = JSON.parseObject(data.get("followReadyResult").toString());
                        if (getIntent().getStringExtra("type").equals("sale")){
                            binding.tvNowBaoPrcie.setText("当前报价"+ data.get("price") +"万");
                            binding.tvNowFloorPrice.setText("当前底价"+ data.get("lowPrice")+"万");
                        }else{
                            binding.tvNowBaoPrcie.setText("当前报价"+ data.get("price") +"元");
                            binding.tvNowFloorPrice.setText("当前底价"+ data.get("lowPrice")+"元");
                        }

                        binding.tvCode.setText(followReadyResult.getString("rscode"));
                        reasonList = JSON.parseObject(followReadyResult.getJSONArray("houseFollowResult").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                        });
                        binding.followReason.setText(reasonList.get(0).get("valueName").toString());
                    }
                });
    }
    //endregion


    //region 保存价格跟进
    private void priceFollowSub(JSONObject jsonObject){
        if (progressDialog!=null && !progressDialog.isShowing()){
            progressDialog.show();
        }
        String url;
        if(getIntent().getStringExtra("type").equals("sale")){
            url = ApiConfig.SAVE_SHS_PRICE_FOLLOW;
        }else{
            url = ApiConfig.SAVE_RENT_PRICE_FOLLOW;
        }

        OkHttpUtils.postString()
                .url(url)
                .content(jsonObject.toString())
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        if (progressDialog!=null && progressDialog.isShowing()){
                            progressDialog.dismiss();
                        }
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (progressDialog!=null && progressDialog.isShowing()){
                            progressDialog.dismiss();
                        }
                        if (Integer.parseInt(String.valueOf(response.get("code"))) == 200){
                            CustomToast.showToast(PushFollowUpActivity.this,"保存成功",1500);
                            finish();
                        }else{
                            CustomToast.showToast(PushFollowUpActivity.this,String.valueOf(response.get("message")),1500);
                        }
                    }
                });
    }
    //endregion
}
